package com.bachongLightNovel.interceptor;

import com.bachongLightNovel.model.pojo.system.User;
import com.bachongLightNovel.utils.JwtUtils;
import com.bachongLightNovel.utils.UserInfoUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author vermouth
 */

@Slf4j
public class UserInfoInterceptor implements HandlerInterceptor {

    /**
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("进入到了用户信息拦截器。。。");
        log.info("请求路径为：{}",request.getRequestURL());
        //获取用户token
        String token = request.getHeader("Token");
        //解析token
        Claims claims = JwtUtils.parseJWT(token);
        User user = new User();
        user.setId(Long.valueOf(claims.get("id").toString()));
        user.setUsername((String) claims.get("username"));
        //将user对象存储到threadLocal当中
        UserInfoUtil.setUser(user);
        return true;
    }

    /**
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
